#include "Morphology.h"

CMorphology::CMorphology(const string& path)
{
	ifstream ifs(path.c_str());
	if(!ifs)
	{
		cerr << "err path : " << path << endl;
		exit(-1);
	}

	cout << "reading Morphology from " << path << " ... ";

	string line;
	int count = 0;

	while(getline(ifs,line))
	{
		line = fs_algo::strip(line);
		if(line.empty() || line[0] == '[')
			continue;

		line = fs_algo::to_lower(line);

		vector<string> items = fs_algo::split(line);
		vector<string> items_sub = fs_algo::split(items[2],",");

		vector<string> content_cur;

		content_cur.push_back(items[0]);
		index[items[0]].push_back(make_pair(count,0));

		for(int i=0; i<(int)items_sub.size(); i++)
		{
			content_cur.push_back(items_sub[i]);
			index[items_sub[i]].push_back(make_pair(count,i+1));
		}

		content.push_back(content_cur);

		count += 1;
	}

	cout << "succeed" << endl;

	/*
	// check multi-mapping index
	for(map<string,vector<pair<int,int> > >::iterator it = index.begin();
		it != index.end();
		it ++)
	{
		if(it->second.size() > 1)
		{
			cout << it->first << endl;
		}
	}
	*/
}

void CMorphology::full_reform(const string& word, vector<string>& form)
{
	form.clear();

	map<string,vector<pair<int,int> > >::iterator it = index.find(word);

	if(index.end() == it || it->second.size() == 0)
	{
		form.push_back(word);
		return ;
	}

	const vector<pair<int,int> >& idxs = it->second;
	for(int i=0; i<(int)idxs.size(); i++)
		form.push_back(content[idxs[i].first][0]);
}

void CMorphology::full_reform_v(const vector<string>& sent, vector<vector<string> >& form)
{
	form.clear();
	form.resize(sent.size());

	for(int i=0; i<(int)sent.size(); i++)
		full_reform(sent[i],form[i]);
}

void CMorphology::reform(string& word)
{
	map<string,vector<pair<int,int> > >::iterator it = index.find(word);

	if(index.end() == it || it->second.size() == 0)
		return ;

	const vector<pair<int,int> >& idxs = it->second;
	word = content[idxs[0].first][0];
}

void CMorphology::reform_v(vector<string>& sent)
{
	for(int i=0; i<(int)sent.size(); i++)
		reform(sent[i]);
}
